﻿using System;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Sustainalytics.Claims;
using Sustainalytics.ClientDW.Entities;
using Sustainalytics.DataLayer.ConnectionStrings;
using Sustainalytics.DataLayer.Shared;
using Sustainalytics.Entities.ConnectionStrings;
using Sustainalytics.Entities.ESGRatings;
using Sustainalytics.ESGRatings.Service.Models;
using Sustainalytics.Utils;
using Sustainalytics.Utils.WebApi.ErrorCodes;
using Sustainalytics.BusinessResearchProductStates.Entities.ResearchState;
using System.Web.Http.Cors;

namespace Sustainalytics.ESGRatings.Service.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [ClaimsChecker("api/v1/esgratingsfilter")]
    [LogControllerFilter(true, true, false)]
    [RoutePrefix("api/v1/esgratingsfilter")]
    public class ESGAdminHelperController : ApiController
    {
        readonly string _urlClientDW;

        readonly string _urlClientPlatform;

        public ESGAdminHelperController()
        {
            this._urlClientPlatform = ConfigurationManager.ConnectionStrings["ClientPlatform"].ConnectionString;
            var connectionStringsManager =
                ConnectionStringsManager.GetInstance(ConnectionStringsRepository.GetInstance(_urlClientPlatform));
            this._urlClientDW = connectionStringsManager.GetConnectionString(ConnectionStringType.ClientDW);
        }

        public ESGAdminHelperController(string urlClientPlatform, string urlClientDW)
        {
            this._urlClientDW = urlClientDW;
            this._urlClientPlatform = urlClientPlatform;
        }


        [Route("")]
        public HttpResponseMessage Get(TestESGRatingOutDto options)
        {
            try
            {//todo: petre review here - no bussines logic layer used 

                var opt = options ?? TestESGRatingOutDto.Default;
                var dto = new TestESGRatingOutDto();

                Action companies = () =>
                {
                    var rep = new RepositoryCollection<CorporateData>(_urlClientDW);
                    var res = rep.ReadWhere(x => x.ComprehensiveEsgResearchState.ResearchState == ResearchState.ResearchAvailable, opt.Skip, opt.Take, null, x => x.Id, x => x.CompanyName);
                    if (res != null)
                        dto.ListCompanies = res.Select(x => new IdNamePair { Id = x.Id, Name = x.CompanyName }).OrderBy(c => c.Name);
                };

                if (opt.OnlyCompanies)
                {
                    companies();
                }
                else
                {
                    var includedFields = new[] { "_id", "Name" };
                    Parallel.Invoke(
                    companies,
                    () =>
                    {
                        var rep = new RepositoryCollection<PeerGroup>(_urlClientDW);
                        var res = rep.ReadAll(includedFields);
                        if (res != null)
                            dto.ListPeerGroups = res.Select(x => new IdNamePair { Id = x.Id, Name = x.Name });
                    },
                    () =>
                    {
                        var rep = new RepositoryCollection<SustainalyticsIndustryGroup>(_urlClientDW);
                        var res = rep.ReadAll(includedFields);
                        if (res != null)
                            dto.ListIndustryGroups = res.Select(x => new IdNamePair { Id = x.Id, Name = x.Name });
                    },
                    () =>
                    {//todo petre  review here  rights to access 
                        var rep = new RepositoryCollection<WeightMatrix>(_urlClientDW);
                        var res = rep.ReadAll(includedFields);
                        if (res != null)
                            dto.ListWeightMatrixes = res.Select(x => new IdNamePair { Id = x.Id, Name = x.Name });
                    },
                    () =>
                    {//todo petre  review here  rights to access 
                        var rep = new RepositoryCollection<ReferenceUniverse>(_urlClientDW);
                        var res = rep.ReadAll(includedFields);
                        if (res != null)
                            dto.ListReferenceUniverses = res.Select(x => new IdNamePair { Id = x.Id, Name = x.Name });
                    });
                }

                return Request.CreateResponse(HttpStatusCode.OK, new { result = dto });
            }
            catch (Exception ex)
            {
                CommonEventSource.Log.Exception(ex);
                return Request.CreateResponse(HttpStatusCode.InternalServerError,
                    new { ErrorStatusCode = WebAPIGeneralErrorCodes.UnhandledException });
            }
        }
    }
}
